<script setup lang="ts">
  import { ref, computed } from 'vue';
  import { MenuItem } from './index';
  const props = defineProps<{
    menuItems: MenuItem[];
  }>();

  const visible = ref(false);
  const position = ref({ x: 0, y: 0 });

  const style = computed(() => ({
    left: position.value.x + 'px',
    top: position.value.y + 'px',
  }));
  const emit = defineEmits(['selectPolicy']); // 声明自定义事件
  const show = (e: MouseEvent) => {
    e.preventDefault();
    position.value = { x: e.clientX, y: e.clientY };
    visible.value = true;

    // 点击其他地方关闭菜单
    document.addEventListener('click', hide);
  };

  const hide = () => {
    visible.value = false;
    document.removeEventListener('click', hide);
  };

  const handleClick = (item: MenuItem) => {
    emit('select', item); // 触发自定义事件，传递菜单项
    item.handler?.();
    hide();
  };

  // 暴露方法给父组件
  defineExpose({ show, hide });
</script>

<template name="contextmenu">
  <div v-show="visible" @blur="hide()" :style="style" class="context-menu">
    <a-list hoverable>
      <a-list-item
        v-for="item in menuItems"
        :key="item.key"
        @click="handleClick(item)"
      >
        <div style="display: flex; align-items: center">
          <svg-icon
            v-if="item.icon"
            :name="item.icon"
            style="width: 1.5em; height: 1.5em"
          />
          <span>{{ item.label }}</span>
        </div>
      </a-list-item>
    </a-list>
  </div>
</template>

<style lang="less" scoped>
  .context-menu {
    position: fixed;
    z-index: 999;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    cursor: default;
    ul {
      list-style: none;
      padding: 5px 0;
      margin: 0;
    }

    li {
      padding: 8px 16px;
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 8px;

      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
</style>
